<template>
  <div>
    <el-card class="role_card1">
      <el-form :inline="true" class="role_form">
        <el-form-item label="职位的搜索">
          <el-input
            v-model="keyWord"
            placeholder="请你输入职位的关键字"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="search" :disabled="!keyWord">搜索</el-button>
          <el-button @click="reset" type="primary">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button @click="addRole" type="primary" icon="Plus">
        添加职位
      </el-button>
      <el-table
        :data="allRole"
        v-loading="loading"
        class="role_table"
        :border="true"
      >
        <el-table-column
          type="index"
          align="center"
          label="#"
        ></el-table-column>
        <el-table-column prop="id" align="center" label="id"></el-table-column>
        <el-table-column
          prop="roleName"
          align="center"
          show-overflow-tooltip
          label="角色名称"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          align="center"
          show-overflow-tooltip
          label="创建时间"
        ></el-table-column>
        <el-table-column
          prop="updateTime"
          align="center"
          show-overflow-tooltip
          label="更新时间"
        ></el-table-column>
        <el-table-column label="操作" width="320">
          <template #="{ row }">
            <el-button @click="setPermisstion(row)" type="primary" icon="User">
              分配权限
            </el-button>
            <el-button @click="updateRole(row)" type="primary" icon="Edit">
              编辑
            </el-button>
            <el-popconfirm
              @confirm="removeRole(row.id)"
              :title="`你确定要删除${row.roleName}?`"
            >
              <template #reference>
                <el-button type="danger" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="prev, pager, next, jumper,-> , sizes, total"
        :total="total"
        @size-change="handler"
        @current-change="getHasRole"
      />
    </el-card>
    <!-- 添加职位与更新已有职位的结构:对话框 -->
    <el-dialog
      v-model="dialogVisite"
      :title="RoleParams.id ? '更新职位' : '添加职位'"
    >
      <el-form :model="RoleParams" :rules="rules" ref="form">
        <el-form-item label="职位名称" prop="roleName">
          <el-input
            v-model="RoleParams.roleName"
            placeholder="请你输入职位名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="danger" @click="dialogVisite = false">取消</el-button>
        <el-button @click="save" type="primary">确定</el-button>
      </template>
    </el-dialog>
    <!-- 抽屉组件:分配职位的菜单权限与按钮的权限 -->
    <el-drawer v-model="drawer" title="分配菜单与按钮权限">
      <!-- 树形控件 -->
      <el-tree
        ref="tree"
        v-loading="loading1"
        :data="menuArr"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="selectArr"
        :props="defaultProps"
      />
      <template #footer>
        <el-button @click="drawer = false">取消</el-button>
        <el-button @click="saveOK" type="primary">确定</el-button>
      </template>
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, nextTick, reactive } from "vue";
import { ElMessage } from "element-plus";
import {
  reqRemoveRole,
  reqAllMenuList,
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqSetPermisstion,
} from "@/api/acl/role";
import type {
  MenuResponseData,
  RoleData,
  RoleResponseData,
  Records,
  MenuList,
} from "@/api/acl/role/type";
import useLayOutSettingStore from "@/store/modules/setting";
let layOutSettingStore = useLayOutSettingStore();
// 判断数据是否全部请求完毕
let loading = ref<boolean>(false);
// 判断数据是否全部请求完毕
let loading1 = ref<boolean>(false);
//分页器当前页码
let pageNo = ref<number>(1);
//每一页展示几条数据
let pageSize = ref<number>(10);
let total = ref<number>(0);
// 搜索职位关键字
let keyWord = ref<string>("");
// 存储全部已有的职位
let allRole = ref<Records>([]);
//控制对话框的显示与隐藏
let dialogVisite = ref<boolean>(false);
//收集新增岗位数据
let RoleParams = reactive<RoleData>({ roleName: "" });
// 获取form组件实例
let form = ref<any>();
// 控制抽屉显示与隐藏
let drawer = ref<boolean>(false);
// 定义数组存储用户权限的数据
let menuArr = ref<MenuList>([]);
// 准备一个数组:数组用于存储勾选的节点的ID(四级的)
let selectArr = ref<number[]>([]);
// 获取tree组件实例
let tree = ref<any>();

onMounted(() => {
  // 获取职位请求
  getHasRole();
});
//获取全部用户信息的方法|分页器当前页码发生变化的回调
const getHasRole = async (pager = 1) => {
  loading.value = await true;
  // 修改当前页码
  pageNo.value = pager;
  let result: RoleResponseData = await reqAllRoleList(
    pageNo.value,
    pageSize.value,
    keyWord.value,
  );
  if (result.code === 200) {
    allRole.value = result.data.records;
    total.value = result.data.total;
  }
  loading.value = await false;
};
// 下拉菜单的回调
const handler = () => {
  getHasRole();
};
// 搜索按钮的回调
const search = () => {
  //根据关键字获取相应的用户数据
  getHasRole();
  //清空关键字
  nextTick(() => {
    keyWord.value = "";
  });
};
// 重置按钮
const reset = () => {
  layOutSettingStore.refsh = !layOutSettingStore.refsh;
};
// 添加职位按钮的回调
const addRole = () => {
  // 对话框显示出来
  dialogVisite.value = true;
  // 清空数据
  Object.assign(RoleParams, {
    roleName: "",
    id: 0,
  });
  nextTick(() => {
    // 清空上一次表单校验错误结果
    form.value?.clearValidate("roleName");
  });
};
// 编辑已有职位按钮的回调
const updateRole = (row: RoleData) => {
  //显示出对话框
  dialogVisite.value = true;
  //存储已有的职位----带有ID的
  Object.assign(RoleParams, row);
  //清空上一次表单校验错误结果
  nextTick(() => {
    form.value?.clearValidate("roleName");
  });
};
// 职位校验规则
const rules = {
  roleName: [
    { required: true, message: "职位名称不能为空！", trigger: "blur" },
    {
      required: true,
      min: 2,
      message: "职位名称至少两位！",
      trigger: "blur",
    },
  ],
};
// 确定按钮的回调
const save = async () => {
  // 表单校验结果,结果通过在发请求、结果没有通过不应该在发生请求
  await form.value.validate(async (valid: any) => {
    if (valid) {
      // 添加职位|更新职位的请求
      let result: any = await reqAddOrUpdateRole(RoleParams);
      if (result.code == 200) {
        // 提示文字
        ElMessage({
          type: "success",
          message: RoleParams.id ? "更新成功" : "添加成功",
        });
        // 再次获取全部的已有的职位
        getHasRole(RoleParams.id ? pageNo.value : 1);
        dialogVisite.value = false;
      } else {
        ElMessage({
          type: "success",
          message: RoleParams.id ? "更新失败" : "添加失败",
        });
      }
    }
  });
};
// 分配权限按钮的回调
const setPermisstion = async (row: RoleData) => {
  // 抽屉显示出来
  drawer.value = true;
  loading1.value = await true;
  Object.assign(RoleParams, row);
  let result: MenuResponseData = await reqAllMenuList(RoleParams.id as number);
  if (result.code === 200) {
    menuArr.value = result.data;
    selectArr.value = filterSelectArr(menuArr.value, []);
  }
  loading1.value = await false;
};
const defaultProps = {
  children: "children",
  label: "name",
};
const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level === 4) {
      initArr.push(item.id);
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr);
    }
  });
  return initArr;
};
// 抽屉确定按钮的回调
const saveOK = async () => {
  // 职位的ID
  const roleId = RoleParams.id;
  // 选中节点的ID
  let arr = tree.value.getCheckedKeys();
  // 半选的ID
  let arr1 = tree.value.getHalfCheckedKeys();
  let result: any = await reqSetPermisstion(roleId as number, [
    ...arr,
    ...arr1,
  ]);
  if (result.code === 200) {
    // 提示文字
    ElMessage({
      type: "success",
      message: "分配权限成功",
    });
    window.location.reload();
    drawer.value = false;
  } else {
    ElMessage({
      type: "success",
      message: "分配权限失败",
    });
  }
};
//删除已有的职位
const removeRole = async (id: number) => {
  let result: any = await reqRemoveRole(id);
  if (result.code == 200) {
    //提示信息
    ElMessage({ type: "success", message: "删除成功" });
    getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1);
  }
};
</script>
<style scoped lang="scss">
.role_card1 {
  margin-bottom: 16px;

  .role_form {
    display: flex;
    justify-content: space-between;

    .el-form-item {
      margin: 0;
    }
  }
}

.role_table {
  margin: 16px 0;
}
</style>
